from lib.common import capture_error
from lib import mybase64
import json
from datetime import datetime
from bson.objectid import ObjectId


def default(obj):
    if isinstance(obj, datetime):
        return obj.__str__()
    if isinstance(obj, ObjectId):
        return str(obj)

    return obj


class CodecJson(object):
    codec_type = "json"

    @staticmethod
    @capture_error
    def decode(msg, trans=False):
        if trans:
            msg = mybase64.decodeWithTrans(msg)

        return json.loads(msg)

    @staticmethod
    def encode(msg):
        return json.dumps(msg, ensure_ascii=False, default=default)

    @staticmethod
    def parse_body(data):
        return data

    @staticmethod
    def fmt_response(result, err, trans=False):
        body = ""
        if result:
            body = result if not trans else mybase64.to_str(mybase64.encodeWithTrans(CodecJson.encode(result)))

        response = {
            "body": body,
            "err": err
        }
        return response


codecJson = CodecJson()
